package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Map;

@Controller
@RequestMapping("/api/payment/alipay")
public class AlipayController {

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PaymentService paymentService;

     @RequestMapping("submit/{orderId}")
     @ResponseBody
     public String submitOrder(@PathVariable(value = "orderId") Long orderId, HttpServletResponse response){
        String from = "";
        try {
            from = alipayService.createaliPay(orderId);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return from;
    }

    // 编写同步回调  http://api.gmall/payment/alipay/callback/return
    @GetMapping("callback/return")
    public String callbackReturn(){
         // 重定向到：return_order_url=http://payment.gmall.com/pay/success.html
        return "redirect:"+ AlipayConfig.return_order_url;
    }



    //  notify_payment_url=http://qgnq4b.natappfree.cc/api/payment/alipay/callback/notify
    //  启动内网穿透工具：
    /**
     * 支付宝异步回调  必须使用内网穿透
     * @param paramMap
     *
     * @return
     */
    @RequestMapping("callback/notify")
    @ResponseBody
    public String alipayNotify(@RequestParam Map<String, String> paramMap) throws AlipayApiException {

        //通过key 获取到对应数据
        String outTradeNo=paramMap.get("out_trade_no");
   //outTradeNo与商家outTradeNo  如果通过这个outTradeNo在交易记录中获取到数据，则说明校验成功
     PaymentInfo paymentInfo= paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
//     if (paymentInfo==null){
//         return "failure";
//     }
//     String totalAmount=paramMap.get("total_amount");
//     if (paymentInfo.getTotalAmount().compareTo(new BigDecimal(totalAmount))!=0){
//         return "failure";
//     }
        //调用SDK验证签名
        boolean flag =AlipaySignature.rsaCheckV1(paramMap,
                                AlipayConfig.alipay_public_key,  //公钥
                                 AlipayConfig.charset,
                                 AlipayConfig.sign_type);
        // 交易状态
        String trade_status = paramMap.get("trade_status");
        String out_trade_no = paramMap.get("out_trade_no");
        if (flag){
            // 验签成功后，按照支付结果异步通知的描述，对支付结果中的业务内容进行二次校验
            //校验后在response中返回success并
            if ("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)) {
                  // 细节：防止万一{当交易状态支付完成，或者交易结束时} 支付状态是CLOSE 或是PAID  则返回failure
                if ("PAID".equals(paymentInfo.getPaymentStatus())  || "CLOSE".equals(paymentInfo.getPaymentStatus())){
                    return "failure";
                }
                // 更新交易记录
                paymentService.paySuccess(outTradeNo,PaymentType.ALIPAY.name(),paramMap);
                return "success";
            }
        }else {
            // TODO 验签失败则记录异常日志，并在response中返回failure.
            return "failure";
        }
        return "failure";
    }


    //  申请退款：
    @GetMapping("refund/{orderId}")
    @ResponseBody
    public Result refund(@PathVariable("orderId") Long orderId){

        //  调用服务层方法
        boolean flag = alipayService.refund(orderId);
        return Result.ok(flag);
    }


    // 关闭支付宝
    @GetMapping("closePay/{orderId}")
    @ResponseBody
    public boolean closePay(@PathVariable("orderId") Long orderId){

        //  调用服务层方法
        boolean flag = false;
        try {
            flag = alipayService.closePay(orderId);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }

    // 查看是否有交易记录
    @RequestMapping("checkPayment/{orderId}")
    @ResponseBody
    public Boolean checkPayment(@PathVariable("orderId") Long orderId){
        // 调用退款接口
        boolean flag = alipayService.checkPayment(orderId);
        return flag;
    }


    // 查询本地是否有交易记录
    @GetMapping("getPaymentInfo/{outTradeNo}")
    @ResponseBody
    public PaymentInfo getPaymentInfo(@PathVariable String outTradeNo){
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(outTradeNo, PaymentType.ALIPAY.name());
        if (null!=paymentInfo){
            return paymentInfo;
        }
        return null;
    }
}